from sqlalchemy.orm import Session
from sqlalchemy import text
import json
from typing import List
from app.entity import SysUser, SysUserRole
from app.schema import UserData
from utils.request import PageInfo
from utils.string import StringUtil

class UserModel:
    """
    菜单管理模块数据库操作层
    """
    @classmethod
    def get_select_options(cls, db: Session):
        opts = db.query(SysUser).filter(SysUser.status==0).all()
        
        return opts

    @classmethod
    def insert(cls, db: Session, data: UserData):
        db_post = SysUser(**data.__dict__)
        db.add(db_post)
        db.commit()
        
        return True

    @classmethod
    def edit(cls, db: Session, post: dict):
        db.query(SysUser).filter(SysUser.user_id == post.get('user_id')).update(post)      
        db.commit()

    @classmethod
    def delete(cls, db: Session, ids: List[int]):
        db.query(SysUser).filter(SysUser.user_id.in_(ids)).delete()
        db.commit()

    @classmethod
    def get_by_id(cls, db: Session, id: int):
        return db.query(SysUser).filter(SysUser.user_id==id).first()
        

    @classmethod
    def get_page(cls, db: Session, where:dict, page: PageInfo ):
        total = db.query(SysUser).filter_by(**where).count()
        rows  = db.query(SysUser).filter_by(**where).offset((page.page-1)*page.limit).limit(page.limit).all()
        
        return total, rows
    
    @classmethod
    def reset_password(cls, db: Session, user_id: int, password: str):
        salt = StringUtil.code_number(6)
        password = StringUtil.gen_password(password, salt)
        db.query(SysUser).filter(SysUser.user_id==user_id).update({'password':password, 'salt':salt})
        db.commit()
        
    @classmethod
    def get_user_roles(cls, db:Session, id:int):
        res = db.query(SysUserRole).filter(SysUserRole.user_id==id).all()
        return [v.role_id for v in res]
    
    @classmethod
    def set_user_roles(cls, db: Session, id:int, ids:List[int]):
        db.query(SysUserRole).filter(SysUserRole.user_id==id).delete()
        for i in ids:
            d = SysUserRole(user_id=id, role_id=i)
            db.add(d)
        db.commit()
        